package com.gongpingjialoan.activity.loans;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.LoginActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.AssessmentData;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.data.CarListFilterData;
import com.gongpingjialoan.data.KCookie;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.JSONUtil;
import com.gongpingjialoan.utility.LoanUtil;
import com.gongpingjialoan.utility.PreferenceUtils;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.UserLocation;
import com.gongpingjialoan.widget.ConfirmDialog;
import com.gongpingjialoan.widget.LoadingDialog;
import com.umeng.socialize.UMShareAPI;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

/**
 * Created by Administrator on 2017/9/21.
 */

public class LoanIndexActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_LOAN = 1001;

    TextView shoufu_lowT, yuegong_lowT;
    TextView modelT, modelDetailT, priceT;
    TextView shouqiT, shouqi_moneyT, monthsT, month_payT;

    JSONArray optionsJsa;
    String from;

    TextView shouqi_desT;
    TextView left_text;
    private LoadingDialog loadingDialog;
    private Toast mToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loan_index);
        setSwipeEnagle();
        initView();
    }

    private void initView() {
        setTitle("贷款");
        setRightImage(R.drawable.kefu_phone, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000253500"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        MiPushClient.setAlias(this, GPJApplication.getInstance().getDeviceCode(), null);
        from = getIntent().getStringExtra("from");
//        if ("home".equals(from)) {//首页进入
        findViewById(R.id.index_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.car_layout).setVisibility(View.GONE);
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionMainView);
//        } else {  //详情进入
//            findViewById(R.id.index_layout).setVisibility(View.GONE);
//            findViewById(R.id.car_layout).setVisibility(View.VISIBLE);
//            PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionSourceView);
//
//            shoufu_lowT = (TextView) findViewById(R.id.shoufu_low);
//            yuegong_lowT = (TextView) findViewById(R.id.yuegong_low);
//            shoufu_lowT.setOnClickListener(this);
//            yuegong_lowT.setOnClickListener(this);
//            modelT = (TextView) findViewById(R.id.model);
//            modelDetailT = (TextView) findViewById(R.id.model_detail);
//            priceT = (TextView) findViewById(R.id.price);
//            Intent it = getIntent();
//            modelT.setText(it.getStringExtra("model_zh"));
//            modelDetailT.setText(it.getStringExtra("modeldetail"));
//            priceT.setText("全价 " + it.getStringExtra("price") + "万");
//            priceT.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
//            shouqi_desT = (TextView) findViewById(R.id.shouqi_des);
//
//            shouqiT = (TextView) findViewById(R.id.shouqi);
//            shouqi_moneyT = (TextView) findViewById(R.id.shouqi_money);
//            monthsT = (TextView) findViewById(R.id.months);
//            month_payT = (TextView) findViewById(R.id.month_pay);
//
//            getloanoptions();
//        }

        findViewById(R.id.submit).setOnClickListener(this);
        findViewById(R.id.query).setOnClickListener(this);
//        findViewById(R.id.flow).setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
////                deleteLoanStatus();
//                return false;
//            }
//        });
        findViewById(R.id.tell).setOnClickListener(this);
        left_text = (TextView) findViewById(R.id.left_text);
        findViewById(R.id.login_layout).setOnClickListener(this);
        setLeftText();
    }

    //获取贷款选项
    private void getloanoptions() {
        String money = Double.parseDouble(getIntent().getStringExtra("price")) * 10000 + "";
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                hidenProgressDialog();
                try {
                    JSONObject jo = new JSONObject(json);
                    optionsJsa = jo.getJSONArray("options");
                    setOptionBypProportion("0%", optionsJsa);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, 1);
        netDataJson.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + API.new_car_detail_options);
        netDataJson.addParam("money", money);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }

    private void setOptionBypProportion(String proportion, JSONArray jsonArray) {
        if (jsonArray == null) {
            return;
        }
        if (proportion.equals("0%")) {
            shouqiT.setText("首期款");
            shoufu_lowT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
            shoufu_lowT.setTextColor(getResources().getColor(R.color.text_blue));
            yuegong_lowT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            yuegong_lowT.setTextColor(getResources().getColor(R.color.text_black));
            shouqi_desT.setText("元");

        } else {
            yuegong_lowT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
            yuegong_lowT.setTextColor(getResources().getColor(R.color.text_blue));
            shoufu_lowT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            shoufu_lowT.setTextColor(getResources().getColor(R.color.text_black));
            final String sText = "首期款(<font size=\"3\" color=\"#1CAC54\">" + proportion + "</font>" + ")";
            shouqiT.setText(Html.fromHtml(sText));
            shouqi_desT.setText("万");
        }
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jo = jsonArray.getJSONObject(i);
                if (proportion.equals(JSONUtil.getString(jo, "proportion"))) {
                    Double shouqi = JSONUtil.getDouble(jo, "advance") / 10000;
                    double shouqiw = new BigDecimal(shouqi+"").setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    if (shouqiw == 0) {
                        shouqi_moneyT.setText(0 + "");
                    } else {
                        shouqi_moneyT.setText(shouqiw + "");
                    }

                    java.text.DecimalFormat df = new java.text.DecimalFormat("##,###,###");
                    int month_pay = new BigDecimal(JSONUtil.getDouble(jo, "month_pay")+"").setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                    month_payT.setText(df.format(month_pay) + "");
                    monthsT.setText("月供(" + JSONUtil.getString(jo, "months") + "期)");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_layout:
                if (GPJApplication.getInstance().isLogin()) {
                    delete();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(mySelf, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOAN);
                }
                break;
            case R.id.submit:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.MainApplyClick);
//                if ("home".equals(from)) {
//                    PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionMainApply);
//                } else {
//                    PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionSourceApply);
//                }

                if (GPJApplication.getInstance().isLogin()) {
                    getLoanStatus();
                } else {
                    Intent intent = new Intent();
                    intent.setClass(mySelf, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOAN);
                }
                break;
            case R.id.query:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.MainCreditClick);
//                if ("home".equals(from)) {
//                    PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionMainCredit);
//                } else {
//                    PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionSourceCredit);
//                }
                if (GPJApplication.getInstance().isLogin()) {
                    getLoanStatus();
//                    deleteLoanStatus();
//                    Intent intent = new Intent(mySelf,LoanDocumentsActivity.class);
//                    startActivity(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(mySelf, LoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOAN);
                }
                break;

            case R.id.yuegong_low:
                setOptionBypProportion("30%", optionsJsa);
                break;

            case R.id.shoufu_low:
                setOptionBypProportion("0%", optionsJsa);
                break;

            case R.id.tell:
                if ("home".equals(from)) {
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionMainService);
                } else {
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionSourceService);
                }

                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4000253500"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;

            default:
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
        if ("home".equals(from)) {
            PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionMainBack);
        } else {
            PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanIntroductionSourceBack);
        }

    }

    private void deleteLoanStatus() {
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                Toast.makeText(mySelf, "sucss", Toast.LENGTH_SHORT).show();
//                LoanUtil.toLoanData(json);
//                LoanUtil.goToPerfect(mySelf);
            }
        }, 1);
        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.campaigncars_evaluations);
        netDataJson.setUseOtherDomain(true);
//        netDataJson.request("delete");
    }

    private void getLoanStatus() {
        showProgressDialog();
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                hidenProgressDialog();
                uploadcity();
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mySelf, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if ("car_detail".equals(getIntent().getStringExtra("from"))) {
                        JSONObject brand_jo = new JSONObject();
                        try {
                            brand_jo.put("brand", getIntent().getStringExtra("brand"));
                            brand_jo.put("brand_zh", getIntent().getStringExtra("brand_zh"));
                            brand_jo.put("model", getIntent().getStringExtra("model"));
                            brand_jo.put("model_zh", getIntent().getStringExtra("model_zh"));
                            brand_jo.put("price", getIntent().getStringExtra("price"));
                            brand_jo.put("year", getIntent().getStringExtra("year_string"));
                            brand_jo.put("mile", getIntent().getStringExtra("mile"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        JSONObject dataJo = JSONUtil.getJSONObject(jo, "data");
                        dataJo.put("infos", brand_jo.toString());
                        uploadInfos(brand_jo.toString());
                    }
                    LoanUtil.toLoanData(jo.toString());
                    LoanUtil.goToPerfect(mySelf);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);
        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.campaigncars_evaluations);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_LOAN) {
                setLeftText();
                getLoanStatus();
            }
        }
    }

    private void uploadInfos(String infos) {

        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onDataJsonUpdate(String json) {
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mySelf, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    LoanUtil.toLoanData(json);
//                    LoanUtil.goToPerfect(mySelf);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.perfect_evaluations);
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("step", "infos");
        netDataJson.addParam("infos", infos);
        netDataJson.request("put");
    }


    private void uploadcity() {

        if (TextUtils.isEmpty(UserLocation.getInstance().getCity())) {
            return;
        }

        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
            }

            @Override
            public void onDataJsonUpdate(String json) {
            }
        }, 1);

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.loan_clues);
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("city", UserLocation.getInstance().getCity());
        netDataJson.request("post");
    }

    private void setLeftText() {
        UserManager mUserManager = new UserManager(mySelf);
        mUserManager = mUserManager.LoadUserInfo();
        if (GPJApplication.getInstance().isLogin()) {
            left_text.setText(mUserManager.getPhone());
            findViewById(R.id.login_img).setVisibility(View.VISIBLE);
        } else {
            left_text.setText("点击登录");
            findViewById(R.id.login_img).setVisibility(View.GONE);
        }
    }

    public void delete() {
        ConfirmDialog dialog = new ConfirmDialog(mySelf, "当前帐号: "+left_text.getText().toString(), new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    UserManager mUserManager = new UserManager(mySelf);
                    mUserManager = mUserManager.LoadUserInfo();
                    loadingDialog = new LoadingDialog(mySelf, "退出账号...");
                    loadingDialog.show();
                    mUserManager.Logout(new UserManager.OnLogoutResponse() {

                        @Override
                        public void onLogoutSuccess() {
                            loadingDialog.dismiss();
                            GPJApplication.getInstance().setIslogin(false);
                            PreferenceUtils mPreferenceUtils = new PreferenceUtils(mySelf);
                            mPreferenceUtils.clearObject(UserManager.class);
                            mPreferenceUtils.clearObject(KCookie.class);

                            setLeftText();
                        }

                        @Override
                        public void onLogoutError(String errorMessage) {
                            loadingDialog.dismiss();
                            Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
        dialog.show();
    }
    private boolean isExit = false;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            isExit = false;
        }
    };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                mToast = Toast.makeText(this, "再按一次退出程序",
                        Toast.LENGTH_SHORT);
                mToast.show();
                mHandler.postDelayed(runnable, 2000);
            } else {
                mToast.cancel();
                StepMonitor.getInstance().addMonitorSend(new Monitor("enter", "exit", System.currentTimeMillis(), 1f));
                StepMonitor.getInstance().isClose = true;
                finish();
//
            }

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
        CarListFilterData.getInstance().clear();
        AssessmentData.getInstance().clear();
    }
}
